package thread;

import java.util.PriorityQueue;

// 记录任务
class MyTimerTask implements Comparable<MyTimerTask> {

    // 要执行的任务
    private Runnable task;
    // 记录任务执行的时刻(时间戳1970.1.1)
    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public long getTime() {
        return this.time;
    }

    public void run(){
        task.run();
    }
}
// 定时器
class MyTimer{
    // 优先级队列存储所有要执行的任务
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public void schedule(Runnable task, long delay){
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    public MyTimer(){
        // 创建一个线程，用来执行队列中的任务
        Thread t = new Thread(()->{
            try{
                while(true){
                    synchronized (locker){
                        // 取出队首元素
                        // wait 和 while 保证每次等待后重新判断
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        // 取出任务
                        MyTimerTask task = queue.peek();

                        if(task.getTime() > System.currentTimeMillis()){
                            // 如果任务执行时间大于系统当前时间，说明执行时间未到，等待差值时间后执行else
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }
                        else{
                            // 时间到了，执行任务
                            task.run();
                            queue.poll();
                        }
                    }
                }
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });
        t.start();
    }
}
public class Demo28 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable(){

            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable(){

            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        timer.schedule(new Runnable(){

            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
    }
}
